package com.devframe.web.taglib;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.Tag;

import com.devframe.sys.util.common.StringUtils;


/**
 * 
 * <pre>
 * &lt;b&gt;&lt;font color=&quot;blue&quot;&gt;RadioTag&lt;/font&gt;&lt;/b&gt;
 * </pre>
 * 
 * <pre>
 * &lt;b&gt; --拼接字符串--&lt;/b&gt;
 * </pre>
 * <pre>
 * 支持array\list\map
 * 支持默认值
 * </pre>
 * <pre>
 * &lt;b&gt;--样例--&lt;/b&gt;
 *   RadioTag obj = new RadioTag();
 *   obj.method();
 * </pre>
 * 
 * JDK版本：JDK1.4
 * 
 * 
 */
public class JoinTag extends AbstractBaseTag {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6580692676812209117L;

	/**
	 * 选项列表数据，可以是list,iterator,array,map等类型，可以使用request中的名字或者通过${}获取的对象。从其他对象的属性得到的数据需要使用EL表达式获取
	 */
	private Object items = null;
    /**
     * 字符串拼接的分隔符,默认逗号。
     */
	private String split=",";
	/**
	 * 用于从对象中获取值，可以为空
	 */
	private String valueField;// 

    

	// ////////////////////////////////////////////
	/**
	 * 标签处理逻辑，生成option列表
	 * @return SKIP_BODY
	 */
	public int doStartTag() {
	    return Tag.SKIP_BODY;
		
	}

	
    /**
     * 标签结束
     * @return EVAL_PAGE
     * @exception JspException JspException
     */
	public int doEndTag() throws JspException {
	    try {
	        this.getBodyContent();
            if (items == null || items.equals("")) {
                return EVAL_PAGE;
            }
            Object options = items;
            if (items instanceof String) {
                options = findAttribute((String) items);
            }
            if (options == null) {
                return EVAL_PAGE;
            }
            List<Object> values=new ArrayList();
            
            int i = 0;
            if (options instanceof Map) {
                Map map = (Map) options;
                if("key".equals(valueField)){
                    values.addAll(map.keySet());
                    valueField = null;
                } else {
                    values.addAll(map.values());
                }
            } else if (options instanceof Collection) {
                values.addAll((Collection)options);
            } else if (options instanceof Iterator){
                Iterator it = (Iterator) options;
                while (it.hasNext()) {
                    Object entry = it.next();
                    values.add(entry);
                    i++;
                }
            } else if (options.getClass().isArray()) {// 数组
                int length = Array.getLength(options);
                for (int j = 0; j < length; j++) {
                    Object entry = Array.get(options, j);
                    values.add(entry);
                    i++;
                }
            }
            String result = joinValues(values,valueField);

			JspWriter writer = null;
			try {
				writer = this.getPreviousOut();
			} catch (Exception e1) {
				writer = pageContext.getOut();
			}

			try {
				writer.print(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return Tag.EVAL_PAGE;
		} catch (Exception e) {
			return EVAL_PAGE;
		}
	}

	/**
	 * joinValues 拼接字符串
	 * @param values values，不能为空
	 * @param property 属性名，可以为空
	 * @return values为空则返回空字符串，否则按split进行拼接
	 * 
	 */
	private String joinValues(List values,String property){
	    if(values==null || values.size()==0){
	        return "";
	    }
	    String[] result = new String[values.size()];
	    Iterator it = values.iterator();
	    int i = 0;
	    while(it.hasNext()){
	        Object obj = it.next();
	        if(property!=null && !"".equals(property)){
	            result[i]=String.valueOf(getPropertyValue(property, obj));
	        } else {
	            result[i]=String.valueOf(obj);
	        }
	        i++;
	    }
	    return StringUtils.arrayToString(result, split);
	}
	
    /**
     * 释放，清空结果
     */
	public void release() {
        this.id=null;
        this.items=null;
        this.valueField=null;
		super.release();
	}

	public Object getItems() {
		return items;
	}

	public void setItems(Object items) {
		this.items = items;
	}

	public void setItems(String items) {
		this.items = items;
	}

	public String getValueField() {
		return valueField;
	}

	public void setValueField(String valueField) {
		this.valueField = valueField;
	}

	public String getSplit() {
		return split;
	}

	public void setSplit(String split) {
		this.split = split;
	}

}
